<template>
    <div class="w-full h-full flex-col">
        <div class="w-full h-75% bg-#f0f0f0/50 flex-col" style="backdrop-filter: blur(4px)">
            <div
                class="w-full box-border p-30px py-10px font-size-1.2rem flex justify-between items-center bg-#ffffff"
            >
                <div>AI Chat</div>
                <n-button text @click="() => emits('back')">
                    <template #icon>
                        <XIcon name="close"></XIcon>
                    </template>
                </n-button>
            </div>
            <div
                class="flex-1 flex-col gap-10px overflow-scroll box-border p-10px"
                style="scrollbar-width: none"
            >
                <div
                    v-for="(item, index) in conversations"
                    :key="index"
                    class="w-full flex"
                    :class="{ 'justify-end': item.role === 'user' }"
                >
                    <div class="flex-col gap-4px">
                        <div
                            class="max-w-500px bg-#ffffff p-10px rounded-8px border-solid"
                            style="word-break: break-all"
                        >
                            {{ item.content }}
                        </div>
                        <div class="flex items-center">
                            <div class="font-size-0.8rem text-gray-400">
                                {{ new Date(item.time).toLocaleString() }}
                            </div>
                            <n-button
                                v-if="item.role !== 'user' && item.queryData"
                                size="tiny"
                                class="ml-auto"
                                @click="jumpToQuery(item.queryData)"
                            >
                                查看详情
                                <XIcon name="forward" :size="10"></XIcon>
                            </n-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="flex-1 flex bg-#ffffff box-border p-16px">
            <div class="flex-col box-border border-solid p-10px rounded-8px w-85% h-full gap-4px">
                <textarea
                    ref="textareaRef"
                    v-model="content"
                    class="flex-1"
                    placeholder="来问点什么吧~"
                />
                <div class="w-full flex justify-end gap-4px">
                    <n-button
                        v-if="user.role === 1"
                        size="tiny"
                        :focusable="false"
                        :type="manageBtnFocus ? 'primary' : ''"
                        @click="
                            () => {
                                manageBtnFocus = !manageBtnFocus
                                searchBtnFocus = false
                                chatModel = chatModel === 'sqlUpdate' ? 'chat' : 'sqlUpdate'
                            }
                        "
                    >
                        <template #icon>
                            <XIcon name="aiManage" :size="16" />
                        </template>
                        智能管理
                    </n-button>
                    <n-button
                        size="tiny"
                        :focusable="false"
                        :type="searchBtnFocus ? 'primary' : ''"
                        @click="
                            () => {
                                searchBtnFocus = !searchBtnFocus
                                manageBtnFocus = false
                                chatModel = chatModel === 'sqlSearch' ? 'chat' : 'sqlSearch'
                            }
                        "
                    >
                        <template #icon>
                            <XIcon name="aiSearch" :size="16" />
                        </template>
                        智能查询
                    </n-button>
                </div>
            </div>
            <div class="flex-1 flex-center">
                <n-button text @click="chat">
                    <n-icon-wrapper :size="48" :border-radius="100">
                        <XIcon name="aiSend" :size="24" color="#ffffff" />
                    </n-icon-wrapper>
                </n-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import XIcon from '@/components/xicon/index.vue'

import { send } from '@/service/api/chat'
import type { MomentVo } from '@/service/types/moment'

const user = JSON.parse(localStorage.getItem('user') || '{}')

class Conversation {
    role: 'user' | 'assistant'
    content: string
    time: number
    queryData?: any

    constructor(role: 'user' | 'assistant', content: string, time: number, queryData?: any) {
        this.role = role
        this.content = content
        this.time = time
        this.queryData = queryData
    }
}

const emits = defineEmits<{
    back: [void]
    query: [MomentVo[]]
}>()

const content = ref('')
const textareaRef = ref<HTMLTextAreaElement | null>(null)

const searchBtnFocus = ref(false)
const manageBtnFocus = ref(false)

const conversations = ref<Conversation[]>([])

const chatModel = ref<'chat' | 'sqlSearch' | 'sqlUpdate'>('chat')

const chat = async () => {
    if (content.value.trim() === '') {
        window.NMessage.warning('请输入内容')
        return
    }
    conversations.value.push(new Conversation('user', content.value, new Date().getTime()))

    try {
        const res: any = await send({
            question: content.value,
            topic: chatModel.value,
            userId: user.id,
        })
        if (chatModel.value === 'chat') {
            conversations.value.push(new Conversation('assistant', res.chat, new Date().getTime()))
        } else if (chatModel.value === 'sqlSearch') {
            conversations.value.push(
                new Conversation('assistant', res.chat, new Date().getTime(), res.queryData)
            )
        } else {
            conversations.value.push(new Conversation('assistant', res.chat, new Date().getTime()))
        }
    } catch (err: any) {
        window.NMessage.error(err.msg || '网络请求错误')
        conversations.value.push(
            new Conversation('assistant', '对话失败，请稍后再试', new Date().getTime())
        )
    } finally {
        content.value = ''
        textareaRef.value!.value = ''
    }
}

const jumpToQuery = (queryData: MomentVo[]) => {
    console.log(queryData)
    queryData.forEach((item) => {
        if (item.location && typeof item.location === 'string') {
            item.location = JSON.parse(item.location as string)
        }
    })
    emits('query', queryData)
}
</script>

<style scoped>
textarea {
    border: none;
    outline: none;
    resize: none;
    scrollbar-width: none;
}
</style>
